<template>
  <a-layout>
    <a-layout-content>
      <a-card v-if="authStore.isAuthenticated" class="create-article">
        <h1>Create New Announcement</h1>
        <a-form :model="article" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-form-item label="Title">
            <a-input v-model:value="article.title" />
          </a-form-item>
          <a-form-item label="Content">
            <a-textarea v-model:value="article.content" :rows="4" />
          </a-form-item>
          <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
            <a-button type="primary" @click="createArticle">Create</a-button>
          </a-form-item>
        </a-form>
      </a-card>
      <div v-else-if="!authStore.isAuthenticated" class="no-data">
        <p>You must log in/register to create an announcement</p>
        <p>You will be redirected to the login page in {{ countdown }} seconds...</p>
      </div>
    </a-layout-content>
  </a-layout>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import axios from "../axios";
import { useRoute, useRouter } from "vue-router";
import type { Article } from "../types/Article";
import { message } from 'ant-design-vue';
import { useAuthStore } from '../store/auth';

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const countdown = ref(5); // 倒计时初始值
// 初始化 article 为一个空的 Article 对象
const article = ref<Article>({
  title: "",
  content: "",
  preview: ""
});


const createArticle = async () => {
  if (!authStore.isAuthenticated) {
    router.push({ name: '' });
    return;
  }
  try {
    // 设置 Preview 为 Content 的前 100 个字符
    if (article.value.content) {
      article.value.preview = article.value.content.substring(0, 100);
    }

    // 构造一个不包含 id 的新对象
    const payload = {
      title: article.value.title,
      preview: article.value.preview,
      content: article.value.content
    };

    await axios.post<Article>("/articles", payload);
    message.success("公告创建成功");


    // 清空表单
    article.value.title = "";
    article.value.content = "";
    article.value.preview = "";
    router.push({ name: 'News' }); // 添加路由跳转
  } catch (error) {
    console.error("Failed to create article:", error);
    message.error("公告创建失败");
  }
};

// 监听未登录状态，启动倒计时
watch(() => authStore.isAuthenticated, (isAuthenticated) => {
  if (!isAuthenticated) {
    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearInterval(timer);
        router.push({ name: 'Auth' });
      }
    }, 1000);
  }
}, { immediate: true }); // 立即执行
</script>

<style scoped>
.create-article {
  margin: 20px 0;
}

.no-data {
  text-align: center;
  font-size: 1.2em;
  color: #999;
}
</style>